package com.ms.dsq_english.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;

import androidx.core.content.FileProvider;


import com.ms.dsq_english.base.BaseApplication;
import com.ms.dsq_english.utils.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import static com.ms.dsq_english.provider.FileProviderPath.DownloadPath;
import static com.ms.dsq_english.utils.FileSizeUtils.formatFileSize;


public class DownloadService extends Service
{
    public static final String TAG = "Download";

    private BaseApplication application;
    private Context mContext = this;
    private String apkFile, apkUrl, apkVersion;
    private int totalSize = 0;

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();

        application = (BaseApplication) getApplication();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        apkFile = getExternalFilesDir("download") + "/danone.apk";
        apkUrl = intent.getStringExtra("url");
        apkVersion = intent.getStringExtra("version");
        totalSize = Integer.parseInt(intent.getStringExtra("totalSize"));

        downloadAPK();

        return super.onStartCommand(intent, flags, startId);
    }

    public void downloadAPK()
    {
//        if (isNewest())
//        {
//            installAPK(new File(apkFile));
//        }
//        else
//        {
//            //清除之前下载好的
//            FileClearUtils.deleteFile(new File(apkFile));

            new DownloadTask().execute();
//        }
    }

    //判断路径中的apk是否最新
    private boolean isNewest()
    {
        PackageInfo packInfo = mContext.getPackageManager().getPackageArchiveInfo(apkFile, PackageManager.GET_ACTIVITIES);

        if (packInfo != null)
        {
            int version = packInfo.versionCode;

            LogUtils.showLog(TAG, "apk version=" + version);

            return version >= Integer.parseInt(apkVersion);
        }

        return false;
    }

    //下载到本地后执行安装
    protected void installAPK(File apkFile)
    {
        LogUtils.showLog(TAG, "apk file=" + apkFile.toString());
        application.currentSize = totalSize;

        stopSelf();

        Intent intent = new Intent(Intent.ACTION_VIEW);

        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)

        {
            //要和AndroidManifest中的provider中的android:authorities="com.hxh.fileprovider"一一对应
            //改名称必须唯一，否则出现重复会安装不了
            Uri apkUri = FileProvider.getUriForFile(mContext, DownloadPath, apkFile);

            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }
        else
        {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    public class DownloadTask extends AsyncTask<String, Double, Boolean>
    {
        private int currentSize;

        @Override
        protected Boolean doInBackground(String... params)
        {
            try
            {
                URLConnection connection = new URL(apkUrl).openConnection();

                totalSize = connection.getContentLength();

                InputStream is = connection.getInputStream();

                OutputStream os = new FileOutputStream(apkFile);

                byte[] buff = new byte[1024];
                int len;

                while ((len = is.read(buff)) != -1)
                {
                    currentSize += len;
                    os.write(buff, 0, len);
                    application.currentSize = currentSize;
                    LogUtils.showLog(TAG, "下载中。。。。。");
                    LogUtils.showLog(TAG, "currentSize=" + formatFileSize(currentSize));
//                    LogUtils.showLog(TAG, "totalSize=" + formatFileSize(totalSize));
                }

                is.close();
                os.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();

                return false;
            }

            return true;
        }

        @Override
        protected void onPostExecute(Boolean result)
        {
            super.onPostExecute(result);

            if (result)
            {
                LogUtils.showLog(TAG, "下载完成");

                installAPK(new File(apkFile));
            }
            else
            {
                LogUtils.showLog(TAG, "下载失败");

                stopSelf();
            }
        }
    }
}
